package com.gbb.common.utils;

import java.util.LinkedList;
import java.util.List;

import android.app.Activity;

/**
 * 存放Activity的容器，退出系统
 *
 * @author gaobingbing
 */
public class AppManager {

    /** LinkedList 装Activity **/
    private List<Activity> activityList = new LinkedList<>();

    /**
     * 单例，获取当前实例
     *
     * @return ActivityManagerTool实例
     */
    public static AppManager getInstance() {
        return SingleModel.INSTANCE;
    }


    /**
     * 添加Activity到容器中
     *
     * @param activity Activity
     */
    public void addActivity(Activity activity) {
        if(!activityList.contains(activity)) {
            activityList.add(activity);
        }
    }

    /**
     * 将activity从容器里面移除
     *
     * @param activity Activity
     */
    public void removeActivity(Activity activity) {
        if(activityList.contains(activity)) {
            activityList.remove(activity);
        }
    }

    /**
     * @return 获取容器大小
     */
    public int getActivityCount() {
        return activityList.size();
    }

    /**
     * @return 获取当前Activity
     */
    public Activity getCurrActivity() {
        return activityList.get(activityList.size() - 1);
    }

    /**
     * 关闭除了当前的Activity
     */
    public void finishAllButCurrent() {
        for(int i = 0; i < activityList.size() - 1; i++) {
            Activity activity = activityList.get(i);
            if(activity != null && !activity.isFinishing()) {
                activity.finish();
            }
        }
    }

    public void finishAll() {
        for(Activity activity : activityList) {
            if(activity != null) {
                activity.finish();
            }
        }
    }

    /**
     * 遍历所有Activity并finish
     */
    public void exitSystem() {
        for(Activity activity : activityList) {
            if(activity != null && !activity.isFinishing()) {
                activity.finish();
            }
        }
        System.exit(0);
    }

    private static class SingleModel {

        final static AppManager INSTANCE = new AppManager();
    }

}
